# app/services/permission_service.py
from app import db
from app.models import ChannelPermission, PrivacySetting, ServerMember
import uuid


class PermissionService:
    @staticmethod
    def can_initiate_dm(sender_id, recipient_id, server_id=None):
        """检查用户是否可以向对方发起私聊"""
        recipient_settings = PrivacySetting.query.filter_by(user_id=recipient_id).first()

        if not recipient_settings:
            # 如果用户没有隐私设置，使用默认值
            if not PrivacySetting.query.first():
                # 创建默认设置如果不存在
                default_settings = PrivacySetting(
                    setting_id=str(uuid.uuid4()),
                    user_id=recipient_id,
                    allow_dm_from_all=True,
                    allow_server_dm=True
                )
                db.session.add(default_settings)
                db.session.commit()
            else:
                # 假设默认允许
                if not True:  # 如果默认不允许私聊
                    return False
        else:
            if not recipient_settings.allow_dm_from_all:
                return False

        # 如果私聊来自同一服务器
        if server_id:
            if not recipient_settings.allow_server_dm:
                return False

            # 检查双方都在同一服务器
            sender_member = ServerMember.query.filter_by(
                server_id=server_id, user_id=sender_id
            ).first()

            recipient_member = ServerMember.query.filter_by(
                server_id=server_id, user_id=recipient_id
            ).first()

            if not sender_member or not recipient_member:
                return False

        return True

    @staticmethod
    def set_default_channel_permissions(channel_id, user_id):
        """为新成员设置默认频道权限"""
        permission = ChannelPermission(
            permission_id=str(uuid.uuid4()),
            channel_id=channel_id,
            user_id=user_id,
            can_view=True,
            can_send=True,
            can_manage=False,
            can_connect=True,
            is_muted=False
        )
        db.session.add(permission)